package com.xuzhijie.pms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.xuzhijie.pms.common.Constants;
import com.xuzhijie.pms.entity.Administrator;
import com.xuzhijie.pms.entity.Owner;
import com.xuzhijie.pms.entity.Property;
import com.xuzhijie.pms.exception.PmsServerException;
import com.xuzhijie.pms.service.IAdministratorService;
import com.xuzhijie.pms.service.IOwnerService;
import com.xuzhijie.pms.service.IPropertyService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/file")
public class FileController {


    @Resource
    private IPropertyService iPropertyService;

    @Resource
    private IOwnerService iOwnerService;

    @Resource
    private IAdministratorService iAdministratorService;

    @GetMapping("/ownerExprot")
    public void ownerExprot(HttpServletResponse response) throws IOException{
        // 模拟查询数据
        List<Owner> owners = iOwnerService.list();

        // 创建 ExcelWriter 对象
        ExcelWriter writer = ExcelUtil.getWriter(true);

        writer.write(owners, true);
        // 将 Excel 写入响应
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("业主列表","UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName +".xlsx");
        writer.flush(response.getOutputStream(), true);
        writer.close();
    }

    @GetMapping("/adminExprot")
    public void adminExprot(HttpServletResponse response) throws IOException{
        // 模拟查询数据
        List<Administrator> owners = iAdministratorService.list();

        // 创建 ExcelWriter 对象
        ExcelWriter writer = ExcelUtil.getWriter(true);

        writer.write(owners, true);
        // 将 Excel 写入响应
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("管理员列表","UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName +".xlsx");
        writer.flush(response.getOutputStream(), true);
        writer.close();
    }

    @GetMapping("/propertyExport")
    public void exportToExcel(HttpServletResponse response) throws IOException {
        // 模拟查询数据
        List<Property> properties = queryData();

        for (Property property : properties) {
            if (property.getImgs()!= null && property.getImgs().length() != 0){
                String imageUrlsString = property.getImgs().substring(1, property.getImgs().length() - 1);
                property.setImgs(imageUrlsString);
            }
        }


        // 创建 ExcelWriter 对象
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 设置表头
        writer.addHeaderAlias("id", "编号");
        writer.addHeaderAlias("detail", "房产详情");
        writer.addHeaderAlias("type", "房产类型");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("checkIn", "是否入住");
        writer.addHeaderAlias("buildingNo", "楼栋号");
        writer.addHeaderAlias("number", "门牌号");
        writer.addHeaderAlias("checkInTime", "入住时间");
        writer.addHeaderAlias("owner", "业主");
        writer.addHeaderAlias("area", "面积");
        writer.addHeaderAlias("renovationStatus", "装修情况");
        writer.addHeaderAlias("imgs", "图片路径");
        writer.setOnlyAlias(true);

        writer.write(properties, true);
        // 将 Excel 写入响应
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("房产信息","UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName +".xlsx");
        writer.flush(response.getOutputStream(), true);
        writer.close();
    }

    @GetMapping("/property/model")
    public void uploadModelProperty(HttpServletResponse response) throws IOException{
        // 模拟查询数据
        List<Property> properties = new ArrayList<>();
        Property property = new Property();
        properties.add(property);

        // 创建 ExcelWriter 对象
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 设置表头
        writer.addHeaderAlias("detail", "房产详情");
        writer.addHeaderAlias("type", "房产类型");
        writer.addHeaderAlias("checkIn", "是否入住");
        writer.addHeaderAlias("buildingNo", "楼栋号");
        writer.addHeaderAlias("number", "门牌号");
        writer.addHeaderAlias("area", "面积");
        writer.addHeaderAlias("renovationStatus", "装修情况");
        writer.setOnlyAlias(true);
        writer.write(properties, true);
        // 将 Excel 写入响应
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("房产导入模板","UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName +".xlsx");
        writer.flush(response.getOutputStream(), true);
        writer.close();
    }



    @PostMapping("/importProperty")
    public boolean impProperty(MultipartFile file) throws IOException {
        try {
            InputStream ip = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(ip);
            List<List<Object>> read = reader.read(1);
            List<Property> properties = CollUtil.newArrayList();
            for (List<Object> row : read) {
                Property p = new Property();
                p.setDetail(row.get(0).toString());
                p.setType(Integer.parseInt(row.get(1).toString()));
                p.setCheckIn(Integer.parseInt(row.get(2).toString()));
                p.setBuildingNo(row.get(3).toString());
                p.setNumber(row.get(4).toString());
                p.setArea(Double.parseDouble(row.get(5).toString()));
                p.setRenovationStatus(Integer.parseInt(row.get(6).toString()));
                properties.add(p);
            }
            iPropertyService.saveBatch(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            throw new PmsServerException("格式错误", Constants.ILLEGAL_PARAMETERS);
        }
        return true;
    }

    private List<Property> queryData() {

        List<Property> list = iPropertyService.list();

        return list;
    }


}
